package main

import (
	"context"
	"fmt"
	"log"
	"net"

	"gitlab.com/go-course-project/go15/skills/grpc/interceptors"
	"gitlab.com/go-course-project/go15/skills/grpc/pb"
	"google.golang.org/grpc"
)

// 实现HelloServiceServer接口
type HelloServiceServerImpl struct {
	pb.UnimplementedHelloServiceServer
}

func (i *HelloServiceServerImpl) Hello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
	resp := pb.NewHelloResponse()
	resp.Message = fmt.Sprintf("hello, %s", req.Name)
	return resp, nil
}

// map[rooid:[user_stream]]
func (i *HelloServiceServerImpl) Ping(stream grpc.BidiStreamingServer[pb.Message, pb.Message]) error {
	for {
		_, err := stream.Recv()
		if err != nil {
			return err
		}

		// message rootid
		pong := &pb.Message{Message: "pong"}
		if err := stream.Send(pong); err != nil {
			return err
		}
	}
}

func main() {
	middlewares := interceptors.NewInterceptorImpl()
	server := grpc.NewServer(
		grpc.ChainUnaryInterceptor(middlewares.UnaryServerInterceptor),
		grpc.ChainStreamInterceptor(middlewares.StreamServerInterceptor),
	)

	pb.RegisterHelloServiceServer(server, &HelloServiceServerImpl{})

	// 启动服务
	lis, err := net.Listen("tcp", ":1234")
	if err != nil {
		log.Fatal(err)
	}
	server.Serve(lis)
}
